<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体 -->
    <el-card>
      <el-button type="primary">添加角色</el-button>
      <el-table :data="childrenUser" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scoped">
            <!-- i1==0 给顶端设置border -->
            <el-row
              v-for="(item1, i1) in scoped.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 == 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scoped.row, item1.id)"
                  >{{ item1.authName }} </el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二,三级权限 -->
              <!-- i2==0 给除顶端设置边框线 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 == 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 第二级 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scoped.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 第三级 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightsById(scoped.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scoped">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-lollipop"
              size="mini"
              @click="showSetRightDialogfn(scoped.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        title="提示"
        :visible.sync="showSetRightDialog"
        width="50%"
        @close="setRightDialogClose()"
      >
        <!-- 树状控件 -->
        <el-tree
          :data="rightsList"
          :props="treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defkeys"
          ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showSetRightDialog = false">取 消</el-button>
          <el-button type="primary" @click="allotRights()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
export default {
  data() {
    return {
      // 存储角色列表
      childrenUser: [],
      //设置权限列表显示与隐藏
      showSetRightDialog: false,

      //所有权限数据
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      //默认选中节点的id值
      defkeys: [],
      //当前选中的权限的id
      selectId: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    //获取所有角色列表
    async getUserList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('数据获取失败')
      }
      this.childrenUser = res.data
      // console.log(this.childrenUser);
    },

    //移除角色
    async removeRightsById(role, rightId) {
      // console.log(role.id);
      const select = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (select === 'cancel') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      role.children = res.data
    },

    //显示或隐藏权限分配列表
    async showSetRightDialogfn(role) {
      this.selectId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限失败')
      }
      this.$message.success('成功获取权限')
      this.rightsList = res.data
      // console.log(this.rightsList);

      //递归获取三级节点的id
      // console.log(role);
      this.getleafKey(role, this.defkeys)
      this.showSetRightDialog = true
    },

    //通过递归的方式，获取三级节点下的所有id,并保存到defkeys[]中
    getleafKey(node, arr) {
      //如果是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((element) => {
        this.getleafKey(element, arr)
      })
    },

    //清空defkeys[],防止defkeys[]里面的值累加
    setRightDialogClose() {
      this.defkeys = []
    },

    //获取tree所选中的id
    async allotRights() {
      //返回目前被选中的节点的 key 所组成的数组
      let selectArr1 = this.$refs.treeRef.getCheckedKeys()
      //返回目前半选中的节点的 key 所组成的数组
      let selectArr2 = this.$refs.treeRef.getHalfCheckedKeys()
      const keys = [...selectArr1, ...selectArr2].join(',')
      console.log(keys)
      const {
        data: res,
      } = await this.$http.post(`roles/${this.selectId}/rights`, { rids: keys })
      if (res.meta.status !== 200) {
        this.$message.error('角色授权错误')
      }
      this.$message.success('角色授权成功')
      this.showSetRightDialog = false
      this.getUserList()
    },
  },
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eeeeee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>